package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadLocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
	@Autowired
	private WmNewsMaterialMapper wmNewsMaterialMapper;
	@Autowired(required = false)
	private WmMaterialMapper wmMaterialMapper;
	@Autowired
	private WmNewsAutoScanService wmNewsAutoScanService;

	/**
	 * 查询文章
	 *
	 * @param dto
	 * @return
	 */
	@Override
	public ResponseResult findAll(WmNewsPageReqDto dto) {
		//1.参数校验
		//分页页码校验
		dto.checkParam();
		//2.执行分页查询
		IPage<WmNews> ipage = new Page<>(dto.getPage(), dto.getSize());
		LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
		//判断状态
		if (dto.getStatus() != null) {
			queryWrapper.eq(WmNews::getStatus, dto.getStatus());
		}
		//频道条件id
		if (dto.getChannelId() != null) {
			queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
		}
		//关键字判断
		if (StringUtils.isNoneBlank(dto.getKeyword())) {
			queryWrapper.like(WmNews::getTitle, dto.getKeyword());
		}
		//时间判断
		if (dto.getBeginPubdate() != null && dto.getEndPubdate() != null) {
			queryWrapper.between(WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate());
		}
		//用户id判断
		queryWrapper.eq(WmNews::getId, WmThreadLocalUtil.getWmUser().getId());
		IPage<WmNews> resultPage = page(ipage, queryWrapper);
		//返回数据
		ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) resultPage.getTotal());
		result.setData(resultPage.getRecords());
		return result;
	}

	/**
	 * 保存修改文章
	 *
	 * @param dto
	 * @return
	 */
	@Override
	public ResponseResult submit(WmNewsDto dto) {
		//1.参数校验
		if (dto.getContent() == null) {
			return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "内容不存在");
		}
			//当自动时，重新赋值为空
		if (dto.getType()==-1){
			dto.setType(null);
		}
		//2.保存和修改文章
		WmNews wmNews = new WmNews();
		BeanUtils.copyProperties(dto, wmNews);
		//处理封面
		wmNews.setImages(StringUtils.join(dto.getImages(), ","));
		//处理时间
		wmNews.setCreatedTime((new Date()));
		wmNews.setSubmitedTime(new Date());
		//处理用户id
		wmNews.setUserId(WmThreadLocalUtil.getWmUser().getId());
		saveOrUpdateWmNews(wmNews);
		//3.判断是否为草稿
		//如果是草稿，那么终止程序
		if (dto.getStatus() == 0) {
			return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
		}
		//如果不是，就提交审核
		//从内容中抽取图片的集合
		List<String> imagerUrlList = getFromImageContent(wmNews);
		//4.关联内容中的图片与文章关系
		contentImageToNews(wmNews, imagerUrlList, WemediaConstants.WM_CONTENT_REFERENCE);

		//5.关联封面中图片与文章关系
		fengmianImageToNews(wmNews, dto, imagerUrlList, WemediaConstants.WM_COVER_REFERENCE);
		//异步调用文章审核业务
		wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
		//6.返回数据
		return ResponseResult.okResult("发布成功");
	}

	private void contentImageToNews(WmNews wmNews, List<String> imagerUrlList, Short type) {
		//根据素材url集合获取对应的素材id集合
		List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imagerUrlList));
		List<Integer> imageIdList = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
		//插入中间表
		wmNewsMaterialMapper.saveRelations(imageIdList, wmNews.getId(), type);
	}

	private void saveOrUpdateWmNews(WmNews wmNews) {
		if (wmNews.getId() != null) {
			//如果是修改，删除中间表，再修改wm—news表
			wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getId, wmNews.getId()));
			updateById(wmNews);
		} else {
			//如果是保存，就直接插入wm——news表
			save(wmNews);
		}
	}

	private List<String> getFromImageContent(WmNews wmNews) {
		List<String> imageList = new ArrayList<>();
		//获取文章内容
		String content = wmNews.getContent();
		//把字符串转换为List<Map>
		List<Map> contentList = JSONArray.parseArray(content, Map.class);
		if (contentList != null) {
			for (Map map : contentList) {
				//是图片
				if (map.get("type").equals("image")) {
					String imageUrl = (String) map.get("value");
					imageList.add(imageUrl);
				}
			}
		}
		return null;
	}

	private void fengmianImageToNews(WmNews wmNews, WmNewsDto dto, List<String> imageUrlList, Short type) {
		//获取封面中的图片
		List<String> images = dto.getImages();
		//如果是自动化
		if (imageUrlList.size() == -1) {
			//从内容中获取图pain
			if (imageUrlList.size() >= -1 && imageUrlList.size() < 3) {
				images = imageUrlList.stream().limit(1).collect(Collectors.toList());
				wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
			}
			if (imageUrlList.size() >= 3) {
				images = imageUrlList.stream().limit(3).collect(Collectors.toList());
				wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
			} else {
				wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
			}
			//修改wm_news表
			wmNews.setImages(StringUtils.join(images, ","));
			updateById(wmNews);
		}
		//根据素材url集合获取对应的素材id集合
		contentImageToNews(wmNews, images, type);
	}
}